package com.tk.remotecontrol

import android.app.AlertDialog
import android.content.*
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment




class OperationPanelFragment : Fragment() {
    private lateinit var container: ConstraintLayout
    private var ipGetUtils : IpGetUtils? = null
    private var serverIp: String? = null
    private var clientIp: String? = null

    private lateinit var viewIpText: TextView
    private lateinit var viewStateText: TextView
    private lateinit var buttonConectServer: Button
    private lateinit var buttonUp: Button
    private lateinit var buttonDown: Button
    private lateinit var buttonLeft: Button
    private lateinit var buttonRight: Button
    private lateinit var buttonStop: Button
    private lateinit var buttonServoUpLeft: Button
    private lateinit var buttonServoUpRight: Button
    private lateinit var buttonServoDownLeft: Button
    private lateinit var buttonServoDownRight: Button
    private lateinit var viewRemotePicture: ImageView


    private var transferSocketService: TransferSocketService? = null


    private val transferSocketServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, binder: IBinder) {
            var serviceBinder = binder as ITransferSocketServiceBinder
            transferSocketService = serviceBinder.getService()
            transferSocketService?.receiveVideoListenerInitialize()
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            transferSocketService?.close()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val context = requireContext();

        ipGetUtils = IpGetUtils(context)
        clientIp = ipGetUtils?.getLocalIpAddress()

        val transferSocketService = Intent(context, TransferSocketService::class.java)
        context.bindService(transferSocketService, transferSocketServiceConnection, Context.BIND_AUTO_CREATE)

        return inflater.inflate(R.layout.fragment_operation_panel, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        container = view as ConstraintLayout

        viewIpText = view.findViewById<TextView>(R.id.text_ip)
        viewStateText = view.findViewById<TextView>(R.id.text_state)
        viewRemotePicture = view.findViewById<ImageView>(R.id.view_remote_image)
        buttonUp = view.findViewById<Button>(R.id.button_up)
        buttonDown = view.findViewById<Button>(R.id.button_down)
        buttonLeft = view.findViewById<Button>(R.id.button_left)
        buttonRight = view.findViewById<Button>(R.id.button_right)
        buttonStop = view.findViewById<Button>(R.id.button_stop)
        buttonConectServer = view.findViewById<Button>(R.id.button_conect_server)
        buttonServoUpLeft = view.findViewById<Button>(R.id.servo_up_left)
        buttonServoUpRight = view.findViewById<Button>(R.id.servo_up_right)
        buttonServoDownLeft = view.findViewById<Button>(R.id.servo_down_left)
        buttonServoDownRight = view.findViewById<Button>(R.id.servo_down_right)

        viewIpText.setText(clientIp)

        buttonUp.setOnClickListener {
            sendCommand("a")
        }
        buttonDown.setOnClickListener {
            sendCommand("b")
        }
        buttonLeft.setOnClickListener {
            sendCommand("c")
        }
        buttonRight.setOnClickListener {
            sendCommand("d")
        }
        buttonStop.setOnClickListener {
            sendCommand("e")
        }

        buttonServoUpLeft.setOnClickListener {
            sendCommand("i")
        }
        buttonServoUpRight.setOnClickListener {
            sendCommand("h")
        }
        buttonServoDownLeft.setOnClickListener {
            sendCommand("g")
        }
        buttonServoDownRight.setOnClickListener {
            sendCommand("f")
        }

        buttonConectServer.setOnClickListener {
            showInputDialog()
        }
    }
    fun sendCommand(cmd: String){
        transferSocketService?.transferCommand("cmd:"+cmd)
    }

    fun showInputDialog() {
        if(clientIp == null){
            Toast.makeText(requireContext(),"请确保已连接WIFI", Toast.LENGTH_LONG)
            return
        }
        val context = requireContext()
        val builder = AlertDialog.Builder(context)
        builder.setTitle("输入服务端ip")
        val dialogView = View.inflate(context,R.layout.content_edittext_dialog, null)
        var dialogEdittext = dialogView.findViewById<EditText>(R.id.dialog_edittext)
        var pref = context.getSharedPreferences("data", Context.MODE_PRIVATE)
        var ip: String? = pref.getString("serverIp", "")
        dialogEdittext.setText(ip)
        builder.setView(dialogView)
        builder.setPositiveButton("确定", object: DialogInterface.OnClickListener {
            override fun onClick(dialog:DialogInterface, which:Int){
                updateStateText("-")
                serverIp = dialogEdittext.text.toString()
                if(serverIp!=""){
                    var editor = context.getSharedPreferences("data",Context.MODE_PRIVATE).edit();
                    editor.putString("serverIp",serverIp);
                    editor.commit();
                    transferSocketService?.setCommandServerIp(serverIp!!)
                    transferSocketService?.transferCommand("ip:" + clientIp)
                }
            }
        });
        builder.setNegativeButton("取消", null);

        builder.show()
    }


    private fun updateStateText(text: String) {
        viewStateText.setText(text)
    }

    override fun onResume() {
        super.onResume()
        requireContext().registerReceiver(
            broadcastReceiver,
            intentFilter()
        )
    }

    override fun onPause() {
        super.onPause()
        requireContext().unregisterReceiver(broadcastReceiver)
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        requireContext().unbindService(transferSocketServiceConnection)
    }


    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action

            if(TransferSocketService.VIDEOPICTURE.equals(action)){
                val bytes = intent.getByteArrayExtra("data")
                var bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

                viewRemotePicture.setImageBitmap(bitmap)
            }
            else if(TransferSocketService.SENTERROR.equals(action)){
                updateStateText("发送失败")
            }
            else if(TransferSocketService.SENTOK.equals(action)){
                updateStateText("发送成功")
            }
        }
    }

    private fun intentFilter(): IntentFilter? {
        val intentFilter = IntentFilter()
        intentFilter.addAction(TransferSocketService.VIDEOPICTURE)
        intentFilter.addAction(TransferSocketService.SENTERROR)
        intentFilter.addAction(TransferSocketService.SENTOK)
        return intentFilter
    }


}
